package com.frxuexi.lib_base.mvvm

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.frxuexi.lib_base.entity.Res
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import java.lang.Exception

open class BaseViewModel:ViewModel() {

    fun <T> httpRequest(s:suspend ()->Res<T>,success:(T)->Unit,fail:(String)->Unit){
        viewModelScope.launch {
            try {
                val res = s.invoke()
                if(res.code==200){
                    success(res.data?:res.message as T)
                }else{
                    fail(res.message)
                }
            }catch (e:Exception){
                fail(e.message.toString())
            }
        }
    }

    fun <T> roomRequest(s:()->T,success:(T)->Unit,fail:(String)->Unit){
        viewModelScope.launch {
            try {
                val res = s.invoke()
                if(res!=null){
                    success(res)
                }else{
                    fail("没有数据")
                }
            }catch (e:Exception){
                fail(e.message.toString())
            }
        }
    }

    fun toBody(para:Any):RequestBody{
        val json = Gson().toJson(para)
        return RequestBody.create("application/json".toMediaTypeOrNull(),json)
    }
}